require(['./config'], () => {
    require(['template', 'header', 'footer', 'zoom'], (template, header) => {
        class Detail {
            constructor() {
                this.init().then(() => {
                    this.addToCart()
                  
                    this.zoom()
                  
                })
            }
            init() {
                const id = Number(window.location.search.slice(4))
                return new Promise(resolve => {
                    // 根据id请求详情数据
                    $.get('http://rap2api.taobao.org/app/mock/241299/detail', { id }, resp => {
                        if (resp.code === 200) {
                            const { detail } = resp.body
                            // 由于我们现在用的是rap2接口，detail里没有id，那么我们手动把id加上去
                            // 但是将来换成真实接口以后这里就不需要了
                            // detail.id = id
                            // this.detail = detail
                            this.detail = { ...detail, id }
                            console.log(this.detail)
                            const str = template('detailTemplate', {
                                ...this.detail
                            })
                            $('#goodsinfo').html(str)

                            resolve()
                        }
                    })
                })
                

            }


            addToCart() {
                $('#shopbag').on('click', e => {
                   
                    let cart = localStorage.getItem('cart')
                    if (cart) {
                        cart = JSON.parse(cart)
                        const isExist = cart.some(shop => shop.id === this.detail.id)
                        console.log(this.detail)
                        // var shopcount= $('#badge').val()
                        // console.log(shopcount);
                        if (isExist) {
                            cart = cart.map(shop => {
                                console.log(shop);
                                if (shop.id === this.detail.id) 
                                shop.count++
                                return shop
                            })
                        } else {
                            cart.push({ ...this.detail, count: 1 })
                        }
                        localStorage.setItem('cart', JSON.stringify(cart))
                    } else {
                        localStorage.setItem('cart', JSON.stringify([{ ...this.detail, count: 1 }]))
                    }
                    header.calcnum()
                })
            }
            
            zoom() {
                $('.zoomimg').elevateZoom({
                    gallery: 'smallimgbox'
                })
            }
        }
        new Detail()
    })
})